import requests
from bs4 import BeautifulSoup
import mysql.connector
from collections import Counter
from itertools import chain
from flask import Blueprint
from JsonResult import JsonResult
from flask import Flask, request, jsonify
jiBenFX = Blueprint('jiBenFX', __name__)

host="192.168.186.10"
user="root"
password="123456"
database="ssq"

# 从网上下载拉取ssq数据
def downLoadSsqDatas():
    url = "https://ssq.17500.cn/win/getlist.html&_t=1733744534998"
    data = {
        "lotid": "ssq",
        "page": "1",
        "limit": 100,
        "ish": 0
    }
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
    }

    # 发送 POST 请求
    response = requests.post(url, data=data, headers=headers)

    # 检查响应状态码
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')

        liList = soup.find_all('li')
        datas = []
        for li in liList:
            data = {}
            qiShu = li.find('h3').find('b').text[:7]
            riQi = qiShu[:4] + '-' + li.find('h3').find('i').text[:5]
            rbList = li.find_all('b', class_='rb')
            number = []
            for rb in rbList:
                number.append(rb.text)
            number.append(li.find('b', class_='bb').text)
            # print(number)
            # print(qiShu)
            # print(riQi)
            data['riQi'] = riQi
            data['qiShu'] = qiShu
            data['number'] = number
            datas.append(data)

        return datas
    else:
        print("请求失败，状态码:", response.status_code)

# 保存ssq数据
def saveSsqDatas(ssqDatas):
    conn = mysql.connector.connect(
        host=host,  # MySQL 服务器地址
        user=user,  # MySQL 用户名
        password=password,  # MySQL 密码
        database=database  # 要操作的数据库
    )

    # 创建一个游标对象
    cursor = conn.cursor()

    cursor.execute('select * from t_ssq_result order by qi_shu desc limit 1')
    lastQiShu=''
    lastData =cursor.fetchone()
    if lastData is not None:
        lastQiShu=str(lastData[0])

    datas=[]
    for ssqData in ssqDatas:
        number=ssqData['number']
        qiShu=ssqData['qiShu']
        if qiShu==lastQiShu:
            break
        ssqTuple=(qiShu,ssqData['riQi'],number[0],number[1],number[2],number[3],number[4],number[5],number[6])
        print(ssqTuple)
        datas.append(ssqTuple)

    if len(datas)==0:
        return

    # 执行查询
    cursor.executemany("INSERT INTO t_ssq_result (qi_shu, ri_qi,number1,number2,number3,number4,number5,number6,number7) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", datas)
    conn.commit()
    # 关闭连接
    cursor.close()
    conn.close()

# 打印球的出现号码以及频次
def printBallFrequency(name,numbers):
    lineNum = 5
    temp = 0
    print(name)
    for item in Counter(numbers).most_common():
        temp = temp + 1
        key = item[0]
        value = item[1]
        frequency = value / len(numbers)
        # if frequency < 0.01:
        #     continue
        print(f"号码:{key},次数:{value},频率:{frequency}", end="   ")
        if (temp >= lineNum):
            print()
            temp = 0
    print()
    print()

# 每个号码出现的频率
# 红1，2,3,4,5,6 蓝有哪些号码出现过，分别多少次
def everyBallNumFrequency(datas):
    result=datas
    totalCount= len(result)
    print(f"总次数：{totalCount}")
    print()

    hong1List=[item[2] for item in result]
    hong2List=[item[3] for item in result]
    hong3List=[item[4] for item in result]
    hong4List=[item[5] for item in result]
    hong5List=[item[6] for item in result]
    hong6List=[item[7] for item in result]
    lanList=[item[8] for item in result]

    printBallFrequency('红1',hong1List)
    printBallFrequency('红2',hong2List)
    printBallFrequency('红3',hong3List)
    printBallFrequency('红4',hong4List)
    printBallFrequency('红5',hong5List)
    printBallFrequency('红6',hong6List)
    printBallFrequency('蓝',lanList)

# 获取存储的ssq数据
def getSsqDatas():
    conn = mysql.connector.connect(
        host=host,  # MySQL 服务器地址
        user=user,  # MySQL 用户名
        password=password,  # MySQL 密码
        database=database  # 要操作的数据库
    )

    # 创建一个游标对象
    cursor = conn.cursor()

    cursor.execute('select * from t_ssq_result ')
    result=cursor.fetchall()

    # 关闭连接
    cursor.close()
    conn.close()

    return result

# 红球每个区间的频次信息
def redBallPartitionFrequency(datas):
    dataList=list(chain(*[item[2:8]for item in datas]))
    list1_11=[]
    list12_22=[]
    list23_33=[]
    for data in dataList:
        if data>=1 and data<=11:
            list1_11.append(data)
        elif data>=12 and data<=22:
            list12_22.append(data)
        elif data>=23 and data<=33:
            list23_33.append(data)
    print(list1_11)
    print(list12_22)
    print(list23_33)
    printBallFrequency('1-11',list1_11)
    printBallFrequency('12-22',list12_22)
    printBallFrequency('23-33',list23_33)
    printBallFrequency('1-33',[*list1_11,*list12_22,*list23_33])

def redBallPartitionBallNum(datas):
    for data in datas:
        len1_11=0
        len12_22=0
        len23_33=0

# 基本走势
@jiBenFX.route('/jiBenFX/jiBenZS', methods=[ "POST"])
def jiBenZS():
    params=request.get_json()
    qiShu=params['qiShu']
    datas = getSsqDatas()
    datas=sorted(datas,key=lambda x:x[0],reverse=False)
    results=[]

    # 第一条数据单独处理
    firstResult={}
    firstResult['qiShu']=datas[0][0]
    firstResult['riQi']=datas[0][1]
    totalValue=0
    for redI in range(1,34,1):
        key='redAbsent'+str(redI)
        firstResult[f'{key}']=0
        key = 'redValue' + str(redI)
        firstResult[f'{key}'] = ''
    for redI in range(2,8,1):
        value=datas[0][redI]
        key = 'redValue' + str(value)
        firstResult[f'{key}'] = value
        totalValue=totalValue+value
    firstResult['redTotalValue']=totalValue
    firstResult['redSpanValue']=datas[0][7]-datas[0][2]
    quJian=quJianBi(datas[0])
    firstResult['quJianBi'] = quJian
    jiOu=jiOuBi(datas[0])
    firstResult['jiOuBi'] = jiOu
    for blueI in range(1,17,1):
        key='blueAbsent'+str(blueI)
        firstResult[f'{key}']=0
        key = 'blueValue' + str(blueI)
        firstResult[f'{key}'] = ''
    value = datas[0][8]
    totalValue=totalValue+value
    key = 'blueValue' + str(value)
    firstResult[f'{key}'] = value
    firstResult['totalValue']=totalValue
    results.append(firstResult)


    for rowIndex in range(1,len(datas),1):
        lastResult=results[rowIndex-1]
        currentResult = {}
        currentResult['qiShu'] = datas[rowIndex][0]
        currentResult['riQi'] = datas[rowIndex][1]
        totalValue = 0
        redBalls=[datas[rowIndex][redI] for redI in range(2, 8, 1)]
        for redI in range(1, 34, 1):
            key = 'redAbsent' + str(redI)
            if redI in redBalls:
                currentResult[f'{key}'] = 0
            else:
                lastRedAbsent=lastResult[key]
                lastRedAbsent=lastRedAbsent+1
                currentResult[f'{key}'] = lastRedAbsent
            key = 'redValue' + str(redI)
            currentResult[f'{key}'] = ''
        for redI in range(2, 8, 1):
            value = datas[rowIndex][redI]
            key = 'redValue' + str(value)
            currentResult[f'{key}'] = value
            totalValue = totalValue + value
        currentResult['redTotalValue'] = totalValue
        currentResult['redSpanValue'] = datas[rowIndex][7] - datas[rowIndex][2]
        quJian = quJianBi(datas[rowIndex])
        currentResult['quJianBi'] = quJian
        jiOu = jiOuBi(datas[rowIndex])
        currentResult['jiOuBi'] = jiOu
        value = datas[rowIndex][8]
        for blueI in range(1, 17, 1):
            key = 'blueAbsent' + str(blueI)
            lastBlueAbsent = lastResult[key]
            if value==blueI:
                currentResult[f'{key}'] = 0
            else:
                lastBlueAbsent = lastBlueAbsent + 1
                currentResult[f'{key}'] = lastBlueAbsent

            key = 'blueValue' + str(blueI)
            currentResult[f'{key}'] = ''

        totalValue = totalValue + value
        key = 'blueValue' + str(value)
        currentResult[f'{key}'] = value
        currentResult['totalValue'] = totalValue
        results.append(currentResult)

    results = sorted(results, key=lambda x: x['qiShu'], reverse=True)
    results=results[0:qiShu]

    # 计算出现总次数
    presentTotalNumMap={}
    for redI in range(1,34,1):
        key=f'redAbsent{redI}'
        num = len(list(filter(lambda item: item[key] == 0, results)))
        key = f'redPresentNum{redI}'
        presentTotalNumMap[key]=num
    for blueI in range(1,17,1):
        key=f'blueAbsent{blueI}'
        num = len(list(filter(lambda item: item[key] == 0, results)))
        key = f'bluePresentNum{blueI}'
        presentTotalNumMap[key]=num

    # 计算平均遗漏值
    avgOmitedValueMap={}
    for redI in range(1,34,1):
        totalOmit=0
        lastMaxOmit=0
        key=f'redAbsent{redI}'
        for result in results:
            value=result[key]
            if value==0:
                totalOmit=totalOmit+lastMaxOmit
                lastMaxOmit=0
            else:
                lastMaxOmit=max(lastMaxOmit,value)
        totalOmit = totalOmit + lastMaxOmit
        num=len(list(filter(lambda item: item[key] == 0, results)))
        num=max(num,1)
        avgOmitedValue=int((totalOmit+num-1)/num)
        key = f'redAvgOmitNum{redI}'
        avgOmitedValueMap[key]=avgOmitedValue
    for blueI in range(1,17,1):
        totalOmit=0
        lastMaxOmit=0
        key=f'blueAbsent{blueI}'
        for result in results:
            value=result[key]
            if value==0:
                totalOmit = totalOmit + lastMaxOmit
                lastMaxOmit = 0
            else:
                lastMaxOmit=max(lastMaxOmit,value)
        totalOmit = totalOmit + lastMaxOmit
        num=len(list(filter(lambda item: item[key] == 0, results)))
        num=max(num,1)
        avgOmitedValue=int((totalOmit+num-1)/num)
        key = f'blueAvgOmitNum{blueI}'
        avgOmitedValueMap[key]=avgOmitedValue


    # 计算最大遗漏值
    maxOmitedValueMap = {}
    for redI in range(1, 34, 1):
        key = f'redAbsent{redI}'
        maxOmitValue = max([item[key] for item in results])
        key = f'redMaxOmitNum{redI}'
        maxOmitedValueMap[key] = maxOmitValue
    for blueI in range(1, 17, 1):
        key = f'blueAbsent{blueI}'
        maxOmitValue = max([item[key] for item in results])
        key = f'blueMaxOmitNum{blueI}'
        maxOmitedValueMap[key] = maxOmitValue


    # 计算最大连出数
    maxContinuosNumMap={}
    for redI in range(1, 34, 1):
        maxContinuosNum=0
        lastValue=-1
        continuosNum=0
        key = f'redAbsent{redI}'
        for result in results:
            value=result[key]
            if(value==lastValue):
                continuosNum=continuosNum+1
            elif value==0:
                continuosNum=1
            else:
                continuosNum=0
            lastValue=value
            maxContinuosNum=max(maxContinuosNum,continuosNum)
        key = f'redMaxContinuosNum{redI}'
        maxContinuosNumMap[key] = maxContinuosNum
    for blueI in range(1, 17, 1):
        maxContinuosNum = 0
        lastValue = -1
        continuosNum = 0
        key = f'redAbsent{blueI}'
        for result in results:
            value = result[key]
            if (value == lastValue):
                continuosNum = continuosNum + 1
            elif value==0:
                continuosNum=1
            else:
                continuosNum = 0
            lastValue = value
            maxContinuosNum = max(maxContinuosNum, continuosNum)
        key = f'blueMaxContinuosNum{blueI}'
        maxContinuosNumMap[key] = maxContinuosNum

    returnResult={'table':results,'presentTotalNumMap':presentTotalNumMap,'avgOmitedValueMap':avgOmitedValueMap,'maxOmitedValueMap':maxOmitedValueMap,'maxContinuosNumMap':maxContinuosNumMap}


    # 红球和值进行分析
    redTotalValueList=[item['redTotalValue'] for item in results]
    minRedTotalValue=min(redTotalValueList)
    maxRedTotalValue=max(redTotalValueList)



    return JsonResult.success(returnResult).toJsonString()

# 计算区间比
def quJianBi(data):
    number1_11 = 0
    number12_22 = 0
    number23_33 = 0
    for redI in range(2,8,1):
        value=data[redI]
        if value>=1 and value<=11:
            number1_11=number1_11+1
        elif value>=12 and value<=22:
            number12_22=number12_22+1
        elif value>=23 and value<=33:
            number23_33=number23_33+1
    return f'{number1_11}:{number12_22}:{number23_33}'

# 计算奇偶比
def jiOuBi(data):
    number_ji=0
    number_ou=0
    for redI in range(2,8,1):
        value=data[redI]
        if value%2==0:
            number_ou=number_ou+1
        else:
            number_ji=number_ji+1
    return f'{number_ji}:{number_ou}'


# 同步最新数据
@jiBenFX.route('/jiBenFX/syncLatestData', methods=[ "POST"])
def syncLatestData():
    downloadSsqDatas = downLoadSsqDatas()
    saveSsqDatas(downloadSsqDatas)
    return JsonResult.success({}).toJsonString()

if __name__ == '__main__':
    downloadSsqDatas=downLoadSsqDatas()
    saveSsqDatas(downloadSsqDatas)
    ssqDatas=getSsqDatas()
    everyBallNumFrequency(ssqDatas)
    redBallPartitionFrequency(ssqDatas)

